<template>
    <el-dialog
        title="新建审查规则"
        :visible.sync="visible"
        :close-on-click-modal="false"
        custom-class="rule-edit-dialog"
        :fullscreen="true"
    >
        <div class="rule-edit-container">
            <div class="rule-edit-header">
                <span class="rule-edit-title">新建审查规则</span>
                <div class="rule-edit-actions">
                    <el-button @click="visible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">保存</el-button>
                </div>
            </div>
            <div class="rule-edit-content">
                <div class="rule-edit-form">
                    <el-form ref="form" :model="form" :rules="rules" label-position="top">
                        <el-form-item label="规则名称" prop="ruleName">
                            <el-input
                                v-model="form.ruleName"
                                autocomplete="off"
                                placeholder="请输入规则名称"
                                maxlength="50"
                                show-word-limit
                            ></el-input>
                        </el-form-item>

                        <el-form-item label="风险等级" prop="riskLevel">
                            <div class="risk-level-group">
                                <div
                                    :class="['risk-level-item', 'high-risk', form.riskLevel === 'high' ? 'active' : '']"
                                    @click="form.riskLevel = 'high'"
                                >
                                    高风险
                                </div>
                                <div
                                    :class="['risk-level-item', 'medium-risk', form.riskLevel === 'medium' ? 'active' : '']"
                                    @click="form.riskLevel = 'medium'"
                                >
                                    中风险
                                </div>
                                <div
                                    :class="['risk-level-item', 'low-risk', form.riskLevel === 'low' ? 'active' : '']"
                                    @click="form.riskLevel = 'low'"
                                >
                                    低风险
                                </div>
                            </div>
                        </el-form-item>

                        <el-form-item label="规则描述" prop="ruleDesc">
                            <el-input
                                v-model="form.ruleDesc"
                                autocomplete="off"
                                placeholder="请输入规则描述"
                                type="textarea"
                                :rows="6"
                                maxlength="1000"
                                show-word-limit
                            ></el-input>
                        </el-form-item>

                        <el-form-item label="规则分组" prop="scenarioId">
                            <el-select v-model="form.scenarioId" placeholder="请选择规则分组">
                                <el-option
                                    v-for="item in leftTreeData"
                                    :key="item.id"
                                    :label="item.title"
                                    :value="item.id"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item v-show="false">
                            <el-input v-model="form.ruleSource" value="create"></el-input>
                        </el-form-item>
                    </el-form>
                </div>

                <div class="rule-edit-preview">
                    <el-tabs v-model="activeTab">
                        <el-tab-pane label="结构示例" name="structure">
                            <div class="preview-content">
                                <div class="preview-header">
                                    <div class="preview-title">规则名称</div>
                                    <div class="preview-desc">{{ form.ruleName || '审查合同主体信息是否完整、真实：合同主体信息是否与订立时间的相应主体信息相匹配' }}</div>
                                </div>

                                <div class="preview-section">
                                    <div class="preview-label">风险等级</div>
                                    <div class="preview-risk-level">
                                        <el-tag :type="getRiskLevelType(form.riskLevel)">{{ getRiskLevelText(form.riskLevel) }}</el-tag>
                                    </div>
                                </div>

                                <div class="preview-section">
                                    <div class="preview-label">规则描述</div>
                                    <div class="preview-text">{{ activeExample.description || form.ruleDesc || '（1）审查主体信息是否完整、准确；（2）自然人的主要信息包括：姓名、性别、住所、身份证号码、联系方式、出生日期；单位及其他组织等；（3）法人或者其他组织的主要信息包括：名称、住所、法定代表人名称、统一社会信用代码；（4）审查是否存在主体条款中必要的保密条款；（5）自然人需要监护人的情形，如未成年人、无行为能力或限制民事行为能力人的民事活动，必须经法定监护人同意或由其代理，否则属于效力待定；（6）自然人死亡时，继承人有权继承死者遗留的个人合法财产。' }}</div>
                                </div>

                                <div class="preview-tabs">
                                    <div 
                                        :class="['tab-btn', activeExampleIndex === 0 ? 'active' : '']"
                                        @click="setActiveExample(0)"
                                    >示例1</div>
                                    <div 
                                        :class="['tab-btn', activeExampleIndex === 1 ? 'active' : '']"
                                        @click="setActiveExample(1)"
                                    >示例2</div>
                                    <div 
                                        :class="['tab-btn', activeExampleIndex === 2 ? 'active' : '']"
                                        @click="setActiveExample(2)"
                                    >示例3</div>
                                </div>
                            </div>
                        </el-tab-pane>
<!--                        <el-tab-pane label="效果验证" name="validation">-->
<!--                            <div class="preview-content">-->
<!--                                <div class="validation-empty">-->
<!--                                    <div class="empty-text">请先完成规则编辑</div>-->
<!--                                </div>-->
<!--                            </div>-->
<!--                        </el-tab-pane>-->
                    </el-tabs>
                </div>
            </div>
        </div>
    </el-dialog>
</template>
<script>
    import { ruleInfo, ruleSave, ruleEdit } from "@/api/rule/rule/rule.js";

    export default {
        props: ["leftTreeData"],
        data() {
            return {
                visible: false,
                selLeftTree:{},
                activeTab: 'structure',
                activeExampleIndex: 0,
                examples: [
                    {
                        title: '示例1',
                        description: '（1）审查主体信息是否完整、准确；（2）自然人的主要信息包括：姓名、性别、住所、身份证号码、联系方式、出生日期；单位及其他组织等；（3）法人或者其他组织的主要信息包括：名称、住所、法定代表人名称、统一社会信用代码；（4）审查是否存在主体条款中必要的保密条款；（5）自然人需要监护人的情形，如未成年人、无行为能力或限制民事行为能力人的民事活动，必须经法定监护人同意或由其代理，否则属于效力待定；（6）自然人死亡时，继承人有权继承死者遗留的个人合法财产。'
                    },
                    {
                        title: '示例2',
                        description: '合同审查应当对合同主体的法人资格、合法性和资信状况进行充分调查。主要包括：（1）核查法人或其他组织的主体资格证明文件，如营业执照、组织机构代码证、法定代表人身份证明等；（2）核实自然人的身份证明、民事行为能力状态；（3）审查主体是否具备签订该类合同的特殊资质；（4）审查授权委托书的真实性和有效性；（5）对重要合同进行主体背景调查，评估履约能力和信用状况。'
                    },
                    {
                        title: '示例3',
                        description: '主体错误示例：（1）合同签订主体与实际履约主体不一致；（2）使用已注销或经营异常的主体签订合同；（3）未核实代理人授权的真实性和授权范围；（4）自然人缺乏完全民事行为能力而未经监护人同意；（5）合同主体信息与印章不符；（6）分支机构超出经营范围订立合同；（7）合同主体约定不明确，难以确定权利义务归属。'
                    }
                ],
                form: {
                    id:"",
                    ruleName:"",
                    ruleDesc:"",
                    ruleType:"",
                    ruleSource:"create",
                    riskLevel:"medium",
                    updateTime:"",
                    message:"",
                    scenarioId:"",
                    createUser:"",
                    createTime:"",
                    updateUser:"",
                    isDeleted:"",
                    scenarioIdName:"",
                },
                formLabelWidth: "120px",
                rules: {
                    ruleName: [
                        { required: true, message: "请输入规则名称", trigger: "blur" }
                    ],
                    riskLevel: [
                        { required: true, message: "请选择风险级别", trigger: "change" }
                    ],
                    ruleDesc: [
                        { required: true, message: "请输入规则描述", trigger: "blur" }
                    ],
                    scenarioId: [
                        { required: true, message: "请选择规则分组", trigger: "change" }
                    ]
                },
            };
        },
        computed: {
            activeExample() {
                return this.examples[this.activeExampleIndex];
            }
        },
        methods: {
            init(id, treeId, treeName) {
                this.resetForm();
                //修改
                if (id) {
                    ruleInfo(id).then((resp) => {
                        if (resp.code == 0) {
                            this.$nextTick(() => {
                                this.form = {
                                    ...this.form,
                                    ...resp.data,
                                };
                                this.selLeftTree = {
                                    data: resp.data.scenarioId,
                                    name: resp.data.scenarioIdName
                                }
                            });
                        } else {
                            this.$msg({
                                message: resp.msg,
                                type: "error",
                            });
                        }
                    });
                } else {
                    this.form.scenarioId = treeId;
                    this.selLeftTree = {
                        data: treeId,
                        name: treeName
                    }
                }
                this.visible = true;
            },

            //获取风险级别对应的标签类型
            getRiskLevelType(level) {
                if (level === 'high') return 'danger';
                if (level === 'medium') return 'warning';
                if (level === 'low') return 'info';
                return 'warning';
            },

            //获取风险级别对应的中文文本
            getRiskLevelText(level) {
                if (level === 'high') return '高风险';
                if (level === 'medium') return '中风险';
                if (level === 'low') return '低风险';
                return '中风险';
            },

            //提交表单数据
            submitForm() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        //修改
                        if (this.form.id) {
                            ruleEdit(this.form).then((resp) => {
                                if (resp.code == 0) {
                                    this.$message({
                                        type: "success",
                                        message: "操作成功!",
                                    });
                                    // 将编辑后的规则数据传递给父组件
                                    this.$emit("refreshData", resp.data || this.form);
                                    this.visible = false;
                                } else {
                                    this.$msg({
                                        message: resp.msg,
                                        type: "error",
                                    });
                                }
                            });
                        //新增
                        } else {
                            ruleSave(this.form).then((resp) => {
                                if (resp.code == 0) {
                                    this.$message({
                                        type: "success",
                                        message: "操作成功!",
                                    });
                                    // 将新建的规则数据（包含ID）传递给父组件
                                    this.$emit("refreshData", resp.data || this.form);
                                    this.visible = false;
                                } else {
                                    this.$msg({
                                        message: resp.msg,
                                        type: "error",
                                    });
                                }
                            });
                        }
                    } else {
                        console.log("error submit!!");
                        return false;
                    }
                });
            },
            resetForm() {
                this.form = {
                    id:"",
                    ruleName:"",
                    ruleDesc:"",
                    ruleType:"",
                    ruleSource:"create",
                    riskLevel:"medium",
                    updateTime:"",
                    message:"",
                    scenarioId:"",
                    createUser:"",
                    createTime:"",
                    updateUser:"",
                    isDeleted:"",
                    scenarioIdName:"",
                };
                this.activeTab = 'structure';
                this.activeExampleIndex = 0;
                this.$nextTick(() => {
                    if (this.$refs.form) {
                        this.$refs.form.resetFields();
                    }
                });
            },
            // 设置当前激活的示例
            setActiveExample(index) {
                this.activeExampleIndex = index;
            }
        }
    };
</script>
<style scoped>
.rule-edit-dialog {
    margin: 0;
}

.rule-edit-container {
    padding: 0;
    min-height: calc(100vh - 40px);
    display: flex;
    flex-direction: column;
}

.rule-edit-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #EBEEF5;
    padding: 15px 20px;
}

.rule-edit-title {
    font-size: 18px;
    font-weight: bold;
}

.rule-edit-actions .el-button {
    margin-left: 10px;
}

.rule-edit-content {
    display: flex;
    flex: 1;
    height: calc(100vh - 120px);
}

.rule-edit-form {
    width: 50%;
    padding: 20px;
    overflow-y: auto;
}

.rule-edit-preview {
    width: 50%;
    padding: 20px;
    background-color: #f5f7fa;
    border-left: 1px solid #EBEEF5;
    overflow-y: auto;
}

.risk-level-group {
    display: flex;
    gap: 10px;
}

.risk-level-item {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 8px 20px;
    cursor: pointer;
    text-align: center;
    transition: all 0.3s;
}

.risk-level-item.active {
    color: #fff;
}

.high-risk.active {
    background-color: #F56C6C;
    border-color: #F56C6C;
}

.medium-risk.active {
    background-color: #E6A23C;
    border-color: #E6A23C;
}

.low-risk.active {
    background-color: #909399;
    border-color: #909399;
}

.preview-content {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.preview-header {
    margin-bottom: 20px;
}

.preview-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
}

.preview-desc {
    color: #303133;
    line-height: 1.5;
}

.preview-section {
    margin-bottom: 20px;
}

.preview-label {
    font-size: 14px;
    color: #606266;
    margin-bottom: 8px;
}

.preview-text {
    color: #303133;
    line-height: 1.6;
}

.preview-tabs {
    display: flex;
    border-top: 1px solid #EBEEF5;
    padding-top: 15px;
    margin-top: 15px;
}

.tab-btn {
    padding: 5px 15px;
    cursor: pointer;
    border-radius: 4px;
    margin-right: 10px;
}

.tab-btn.active {
    background-color: #409EFF;
    color: #fff;
}

.validation-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 300px;
}

.empty-text {
    color: #909399;
    font-size: 16px;
}
</style>
